package com.xms.schema.api.controller;

import com.xms.core.exception.XmsException;
import com.xms.core.model.KeyValuePair;
import com.xms.event.core.IEventPublisher;
import com.xms.form.event.CreateDefaultFormEvent;
import com.xms.queryview.event.CreateDefaultViewEvent;
import com.xms.ribbonbutton.event.CreateDefaultButtonsEvent;
import com.xms.schema.api.model.CreateEntityModel;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.Entity;
import com.xms.schema.service.attribute.IDefaultAttributeProvider;
import com.xms.schema.service.entity.IEntityCreaterService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.JsonUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * EntityCreaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/18
 */
@RestController
@RequestMapping("{org}/api/schema/entity")
public class EntityCreaterController extends ApiBaseController {
    private IEntityCreaterService _entityCreaterService;
    private IDefaultAttributeProvider _defaultAttributeProvider;
    private IEventPublisher _eventPublisher;

    @Autowired
    public void EntityCreaterController(IEntityCreaterService entityCreaterService,
                                        IDefaultAttributeProvider defaultAttributeProvider,
                                        IEventPublisher eventPublisher) {
        _entityCreaterService = entityCreaterService;
        _defaultAttributeProvider = defaultAttributeProvider;
        _eventPublisher = eventPublisher;
    }

    @ApiOperation("新建实体")
    @PostMapping("create")
    public JsonResultObject create(@RequestBody CreateEntityModel model) throws XmsException, SQLException {
        if (StringUtil.isEmpty(model.name) || StringUtil.isEmpty(model.name)) {
            return JNotSpecifiedParams("名称");
        }
        Entity entity = new Entity();
        entity.setEntityid(UUIDUtil.get());
        entity.setParententityid(model.parententityid);
        entity.setName(model.name);
        entity.setEntitymask(model.entitymask);
        entity.setAuthorizationenabled(model.authorizationenabled);
        entity.setDuplicateenabled(model.duplicateenabled);
        entity.setIscustomizable(true);
        entity.setLocalizedname(model.localizedname);
        entity.setLogenabled(model.logenabled);
        entity.setWorkflowenabled(model.workflowenabled);
        if (CollectionUtil.notEmpty(model.entitygroupid))
            entity.setEntitygroups(JsonUtil.toJSONString(model.entitygroupid));
        entity.setCreatedby(_currentUser.getUser().SystemUserId);
        entity.setCreatedon(LocalDateTime.now());
        entity.setOrganizationid(_currentUser.getUser().OrganizationId);
        boolean success = _entityCreaterService.create(entity, model.defaultattributes);
        StringBuilder msg = new StringBuilder();
        if (success) {
            msg.append("创建实体成功\n");
            if (model.createDefaultForm) {
                //发布创建默认表单事件
                _eventPublisher.publish(new CreateDefaultFormEvent(entity));
            }
            if (model.createDefaultView && CollectionUtil.notEmpty(model.defaultattributes)) {
                List<Attribute> defaultAttributes = _defaultAttributeProvider.getSysAttributes(entity).attributes;
                defaultAttributes.removeIf(x -> !model.defaultattributes.contains(x.getName()));
                //发布创建默认视图事件
                _eventPublisher.publish(new CreateDefaultViewEvent(entity, defaultAttributes));
            }
            if (CollectionUtil.notEmpty(model.defaultbuttons)) {
                //发布创建默认按钮事件
                _eventPublisher.publish(new CreateDefaultButtonsEvent(entity, model.defaultbuttons));
            }
        }
        return success ? JCreateSuccess(KeyValuePair.build("id", entity.getEntityid())) : JCreateFailure(msg.toString());
    }
}
